package com.wooboo.server.ext.util.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wooboo.dsp.redis.util.RedisClient;
import com.wooboo.server.ext.ApiError;
import com.wooboo.server.ext.Logger;
import com.wooboo.server.ext.data.AdMonitor;
import com.wooboo.server.ext.service.DbService;
import com.wooboo.server.ext.service.PushService;
import com.wooboo.server.ext.util.StringUtil;

public class MonitorUtil {

	public static final Logger logger = Logger.getLogger(MonitorUtil.class);
	public static final String afc="admanage_flow_control_";
	public static final Integer expire_day=60*60*24;
	public static final String IDEA="idea";
	public static final String GROUP = "group";
	public static final String PLAN="plan";
	/**
	 * 获取key
	 * */
	private static String createKeys(AdMonitor m,String date,String type){
		return afc+type+date+m.planId+m.groupId+m.ideaId;
	}
	/**
	 * partten key
	 * */
	private static String createKeysPartten(String date,String type){
		return afc+type+date+"*";
	}
	
	public static Integer monitor2db(String date) throws ApiError{
		List<AdMonitor> list = fatchList(date, PLAN);
		
		DbService dbService = new DbService();
		for(AdMonitor m:list){
			dbService.saveAdmanagePlanLimit(m);
		}
		return list.size();
	}
	
	
	/**
	 * idea
	 * */
	public synchronized static  void checkIdeaId(AdMonitor m,String date) throws ApiError{
		String key=createKeys(m,date,IDEA);
		DbService dbService = new DbService();
		AdMonitor current=null;
		String json = RedisClient.getRedisClient().get(key);
		if(!StringUtil.isEmpty(json)){
			current = JSONObject.toJavaObject(JSON.parseObject(json), AdMonitor.class);
		}else{
			current = dbService.findIdeaMonitor(m.getIdeaId());
		}
		if(null!=current){
			addMonitor(current, m);
			RedisClient.getRedisClient().setex(key,expire_day,JSONObject.toJSONString(current));
		}
		
	}
	/**
	 * 
	 * cpc(2,"cpc"),
        cpm(1,"cpm");
	 * */
	private static void addMonitor(AdMonitor current,AdMonitor m){
		current.setShow(current.getShow()+m.getShow());
		current.setClick(current.getClick()+m.getClick());
		current.setTraffic(current.getTraffic()+m.getTraffic());
		Double money = 0d;
		if(2==current.getBilling_type()){
			money = m.getClick()*current.getPrice();
		}else if(1==current.getBilling_type()){
			money = m.getShow()*current.getPrice()/1000;
		}
		current.setMoney_ad(current.getMoney_ad()+money);

		//今日数据
		current.setTodayClick(current.getTodayClick()+m.getClick());
		current.setTodayShow(current.getTodayShow()+m.getShow());
		current.setTodayTraffic(current.getTodayTraffic()+m.getTraffic());
		current.setTodayMoneyAd(current.getTodayMoneyAd()+money);
		
	}
	
	//================================合并组数据=========================================
	public static void merge2GroupId(String date){
		List<AdMonitor> list = fatchList(date,IDEA);
		Map<String, AdMonitor> map = merge2Group(list);
		for(Entry<String, AdMonitor> en:map.entrySet()){
			AdMonitor ad = en.getValue();
			String key=createKeys(ad,date,GROUP);
			RedisClient.getRedisClient().setex(key,expire_day,JSONObject.toJSONString(ad));
			checkGroupBudget(ad);
		}
	}
	private static void checkGroupBudget(AdMonitor am){
		if(am.getGroup_budget_rmb()-am.getTodayMoneyAd()<=0){
			logger.logInfo("MonitorUtil.checkGroupBudget(group_budget_rmb="+am.getGroup_budget_rmb()+",today="+am.getTodayMoneyAd()+")");
		    PushService pushService = new PushService();
		    pushService.openClose(StringUtil.dealNull(am.getGroupId()), PushService.Action.group_close.toString());
		}
	}
	
	
	private static Map<String, AdMonitor> merge2Group(List<AdMonitor> list){
		Map<String, AdMonitor> map = new HashMap<>();
		
		for(AdMonitor m:list){
			AdMonitor current = map.get(GROUP+m.getGroupId());
			if(current!=null){
				current.setClick(current.getClick()+m.getClick());
				current.setShow(current.getShow()+m.getShow());
				current.setTraffic(current.getTraffic()+m.getTraffic());
				current.setMoney_ad(current.getMoney_ad()+m.getMoney_ad());
				//今日数据
				current.setTodayClick(current.getTodayClick()+m.getClick());
				current.setTodayShow(current.getTodayShow()+m.getTodayShow());
				current.setTodayTraffic(current.getTodayTraffic()+m.getTraffic());
				current.setTodayMoneyAd(current.getTodayMoneyAd()+m.getMoney_ad());
				
			}else{
				map.put(GROUP+m.getGroupId(), m);
			}
		}
		return map;
	}
	//================================合并组数据 结束========================================= 
	public static void merge2PlanId(String date){
		List<AdMonitor> list = fatchList(date,GROUP);
		Map<String, AdMonitor> map = merge2plan(list);
		for(Entry<String, AdMonitor> en:map.entrySet()){
			AdMonitor ad = en.getValue();
			String key=createKeys(ad,date,PLAN);
			RedisClient.getRedisClient().setex(key,expire_day,JSONObject.toJSONString(ad));
			checkPlanBudget(ad);
		}
	}
	private static void checkPlanBudget(AdMonitor am){
		if(am.getTotal_budget_rmb()-am.getMoney_ad()<=0){
			logger.logInfo("MonitorUtil.checkPlanBudget(total_budget_rmb="+am.getGroup_budget_rmb()+",today="+am.getMoney_ad()+")");
			PushService pushService = new PushService();
			pushService.openClose(StringUtil.dealNull(am.getGroupId()), PushService.Action.plan_close.toString());
		}
	}
	private static Map<String, AdMonitor> merge2plan(List<AdMonitor> list){
		Map<String, AdMonitor> map = new HashMap<>();
		
		for(AdMonitor m:list){
			AdMonitor current = map.get(PLAN+m.getGroupId());
			if(current!=null){
				current.setClick(current.getClick()+m.getClick());
				current.setShow(current.getShow()+m.getShow());
				current.setTraffic(current.getTraffic()+m.getTraffic());
				current.setMoney_ad(current.getMoney_ad()+m.getMoney_ad());
				//今日数据
				current.setTodayClick(current.getTodayClick()+m.getClick());
				current.setTodayShow(current.getTodayShow()+m.getTodayShow());
				current.setTodayTraffic(current.getTodayTraffic()+m.getTraffic());
				current.setTodayMoneyAd(current.getTodayMoneyAd()+m.getMoney_ad());
			}else{
				map.put(PLAN+m.getGroupId(), m);
			}
		}
		return map;
	}
	
	public static List<AdMonitor> fatchList(String date,String type){
		List<AdMonitor> list = new ArrayList<>();
		String pattern = createKeysPartten(date, type);
		
		System.out.println(pattern);
		
		
		Set<String> keys = RedisClient.getRedisClient().keys(pattern);
		for(String key:keys){
			System.out.println(key);
			
		    String json = RedisClient.getRedisClient().get(key);
			AdMonitor m = JSONObject.toJavaObject(JSON.parseObject(json), AdMonitor.class);
			list.add(m);
		}
		return list;
	}
	
	
	
	
	
}
